/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.terminalrodoviario.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.terminalrodoviario.Company;
import br.terminalrodoviario.City;
//import br.terminalrodoviario.Encryption;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.fileupload.*;


/**
 *
 * @author TIAGO
 */
public class CompanyServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, FileUploadException, Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("acao");
            String id = request.getParameter("id");
            if(request.getParameter("delete.x") != null || request.getParameter("delete.y") != null)
                delete(request, response);
            else if((request.getParameter("edit.x") != null || request.getParameter("edit.y") != null) && id != null)
                response.sendRedirect("Fields/FCompany.jsp?id="+id);
            else if(action.equalsIgnoreCase("gravar") && id.equals("null"))
                insert(request, response);
            else if(action.equalsIgnoreCase("gravar") && !id.equals("null"))
                update(request, response);
        } finally {
            out.close();
        }
    }

    private void insert(HttpServletRequest request, HttpServletResponse response){
        Company c = new Company();
        PrintWriter out = null;
        try{
            c = fillObject(request);
        }
        catch(Exception e){
            try {
                out = response.getWriter();
            } catch (IOException ex) {
                Logger.getLogger(CompanyServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            e.printStackTrace(out);
            return;
        }
      
        c.insert();      
        try{
            response.sendRedirect("Manager/MCompany.jsp");
        }catch(IOException ex){

        }
    }

    public Company fillObject(HttpServletRequest request) throws FileUploadException, Exception{
            Company c = new Company();
            String root = request.getRealPath("");
            String path = root + "/add/images/companies/";
            String imagem = null;
            boolean isMultipart = FileUpload.isMultipartContent(request);
            if (isMultipart) {
                DiskFileUpload upload = new DiskFileUpload();
                upload.setSizeMax(1024 * 1024); //1Mb
                upload.setRepositoryPath(path);
                List items = upload.parseRequest(request);
                Iterator it = items.iterator();
                String login = ((FileItem)items.get(1)).getString();
                imagem = login + ".jpg";
                while (it.hasNext()) {
                    FileItem fitem = (FileItem) it.next();
                    if (!fitem.isFormField()) {
                        //File f = new File (path+imagem);
                        //f.delete();
                        if(fitem.get() != null){
                            fitem.write(new File(path + imagem));
                            c.setLogo(imagem);
                        }
                        else
                        {
                            String logo = ((FileItem)items.get(18)).getString();
                            c.setLogo(logo);
                        }
                    }
                    else{
                        String nome = fitem.getFieldName();
                        String valor = fitem.getString();
                        if(nome.equals("txtName")){
                            c.setName(valor);
                            continue;
                        }
                        if(nome.equals("txtCNPJ")){
                            c.setCnpj(valor);
                            continue;
                        }
                        if(nome.equals("txtAddress")){
                            c.setAddress(valor);
                            continue;
                        }
                        if(nome.equals("txtCEP")){
                            c.setCep(valor);
                            continue;
                        }
                        if(nome.equals("cboCities")){
                            City ct = new City();
                            ct.setId(Integer.parseInt(valor));
                            c.setCity(ct);
                            continue;
                        }
                        if(nome.equals("txtCorporateName")){
                            c.setCorporateName(valor);
                            continue;
                        }
                        if(nome.equals("txtDateFundation")){
                            DateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
                            df.setLenient (false);
                            Date dt = null;
                            try {
                                dt = df.parse(valor);
                            } catch (ParseException ex) {
                                Logger.getLogger(NoticeServlet.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            c.setDateFundation(dt);
                            continue;
                        }
                        if(nome.equals("txtDescription")){
                            c.setDescription(valor);
                            continue;
                        }
                        if(nome.equals("txtEmail")){
                            c.setEmail(valor);
                            continue;
                        }
                        if(nome.equals("txtFax")){
                            c.setFax(valor);
                            continue;
                        }
                        if(nome.equals("txtLogin")){
                            c.setLogin(valor);
                            continue;
                        }
                        if(nome.equals("txtPassword")){
                            if(valor.equals(request.getParameter("txtOldPassword"))){
                                c.setPassword(valor);
                                continue;
                            }
                            //Encryption e = new Encryption();
                            c.setPassword(valor);//e.encrypt(valor));
                            continue;
                        }
                        if(nome.equals("txtInsertDate")){
                            DateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
                            df.setLenient (false);
                            Date dt = null;
                            try {
                                dt = df.parse(valor);
                            } catch (ParseException ex) {
                                Logger.getLogger(NoticeServlet.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            c.setInsertDate(dt);
                            continue;
                        }
                        if(nome.equals("txtMunicipalRegistration")){
                            c.setMunicipalRegistration(valor);
                            continue;
                        }
                        if(nome.equals("txtPhone")){
                            c.setPhone(valor);
                            continue;
                        }
                        if(nome.equals("txtStateRegistration")){
                            c.setStateRegistration(valor);
                            continue;
                        }
                        if(nome.equals("txtWebsite")){
                            c.setWebSite(valor);
                            continue;
                        }
                    }
                }
            }
            return c;
    }   

    private void delete(HttpServletRequest request, HttpServletResponse response){
       String[] ids = request.getParameterValues("id");
        if (ids != null){
              for(int k = 0; k< ids.length; k++){
                Company c = new Company();
                    c.setId(Integer.parseInt(ids[k]));
                    c.delete();
              }
        }

        try{
            response.sendRedirect("Manager/MCompany.jsp");
        }catch(IOException ex){

        }
    }

    private void update(HttpServletRequest request, HttpServletResponse response) throws FileUploadException, Exception{
        Company c = fillObject(request);
        String id = request.getParameter("id");
        c.setId(Integer.parseInt(id));
        c.update();
        try{
            response.sendRedirect("Manager/MCompany.jsp");
        }catch(IOException ex){

        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(CompanyServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(CompanyServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(CompanyServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(CompanyServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
